import re
from datetime import datetime
from django.shortcuts import render, redirect
from HostManager import SSH
from AppManager import Mysql
from OpManager import settings

MonitData = {"time": datetime.now()}


# Monit监控的页面展示
@settings.auth(AuthType="AppMonitor", AuthNum=3)
def MonitView(requests):
    difftime = (datetime.now() - MonitData["time"]).seconds
    if difftime > 60 * 5:
        print("重新获取Monit监控")
        getAllMonit()
    context = {
        "MonitData": MonitData
    }
    print(context)
    return render(requests, "monit.html", context)


# 新建Monit监控
@settings.auth(AuthType="AppMonitor", AuthNum=3)
def MonitAdd(requests):
    if requests.method == "POST":
        sql = "SELECT * FROM `host` WHERE hostname='%s'" % requests.POST['hostname']
        host = Mysql.MysqlPool(sql, 1)
        sql = "SELECT * FROM `host_dev` WHERE hostname='%s'" % (requests.POST['hostname'])
        hostdev = Mysql.MysqlPool(sql, 1)
        monitstr = "check process %s with pidfile %s\n" \
                   "start program = \"%s\"\n" \
                   "stop program = \"%s\"\n" \
                   "%s" % (requests.POST["process"], requests.POST["pidfile"], requests.POST["start"],
                           requests.POST["stop"], requests.POST["context"])
        command = ["echo \'" + monitstr + "\' > /etc/monit.d/" + requests.POST["process"] + ".monit", "monit reload"]
        res = SSH.SshComm(host["ip"], host["ssh_port"], hostdev["Suser"], hostdev["Spasswd"], command)
        print("重新更新数据")
        getAllMonit()
        if res[command[0]]["stderr"]:
            print(res)
    return redirect('/monitor_monit')


# 获取所有主机的monit信息
def getAllMonit():
    global MonitData
    MonitData = {
        "time": datetime.now(),
        "data": {}
    }
    try:
        # 获取主机的信息
        sql = "SELECT * FROM `host`"
        hosts = Mysql.MysqlPool(sql, 99)
        print("Monit_getALlMonit", hosts)
        sql = "SELECT * FROM `host_dev`"
        hostdevs = Mysql.MysqlPool(sql, 99)
        i = 0
        for host in hosts:
            HostData = {
                "hostname": host["hostname"],
                "host": host["ip"],
                "port": host["ssh_port"],
                "username": hostdevs[i]["Suser"],
                "password": hostdevs[i]["Spasswd"]
            }
            resdict = getMonitData(HostData)
            if resdict:
                MonitData["data"][host["hostname"]] = resdict
    except Exception as e:
        print("获取monit异常", type(e), e)


# 获取Monit信息
def getMonitData(HostData):
    command = ["monit status"]
    res = SSH.SshComm(HostData["host"], HostData["port"], HostData["username"], HostData["password"], command)
    try:
        stderr = res[command[0]]["stderr"]
        if stderr:
            if not stderr.find("is not running") == -1:
                errorcommand = ["monit"]
                print("启动monit")
                res = SSH.SshComm(HostData["host"], HostData["port"], HostData["username"], HostData["password"],
                                  errorcommand)
                print(res[errorcommand[0]]["stderr"])
                res = SSH.SshComm(HostData["host"], HostData["port"], HostData["username"], HostData["password"], command)
            elif not stderr.find("command not found") == -1:
                return None
    except Exception as e:
        print("Monit结果获取异常", type(e), e)
    return monit_str2dict(res[command[0]]["stdout"])


# 将获取到的monit数据转化成标准字典格式
def monit_str2dict(string):
    res = re.split("\n\n", string)
    tmpdict = {
        "title": res.pop(0),
        "datadict": {}
    }
    i = 0
    for data in res:
        index = data.find("\n")
        if not data[0:index]:
            continue
        if i:
            tmpdict["datadict"][data[0:index]] = {
                "res": data[index + 1:]
            }
        else:
            tmpdict["datadict"][data[0:index]] = {
                "active": " active",
                "show": " active show",
                "res": data[index + 1:]
            }
            i = 1
    return tmpdict


getAllMonit()
